<template>
    <div class="attributePage">
        <div class="default-action">
            <div class="select-all">
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange" :disabled="props.isRead">
                    <span>全选</span>
                </el-checkbox>
            </div>
            <el-checkbox-group v-model="attributeObj.checkedDefaultCheckList" @change="handleCheckedChange" :disabled="props.isRead">
                <el-checkbox v-for="(item, index) in attributeObj.defaultCheckList" :key="index" :value="item.value" class="act-item">
                    <span>{{ item.label }}</span>
                </el-checkbox>
            </el-checkbox-group>
        </div>
    </div>
</template>

<script setup lang="ts">

const props = defineProps({
    isRead: {
        type: Boolean,
        default: false,
    }
})
const attributeObj = inject('attributeObj',ref())
const checkAll = ref(false)
const isIndeterminate = ref(false)
const handleCheckAllChange = (val: boolean) => {
    attributeObj.value.checkedDefaultCheckList = val ? attributeObj.value.defaultCheckList.map((item:any) => item.value) : []
    isIndeterminate.value = false
}
const handleCheckedChange = (value: string[]) => {    
    const checkedCount = value.length
    checkAll.value = checkedCount === attributeObj.value.defaultCheckList.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < attributeObj.value.defaultCheckList.length
}
// 使用 watch 监听 attributeObj 的变化
watch(attributeObj, (newVal) => {
    handleCheckedChange(newVal.checkedDefaultCheckList);
    // console.log('选中:',attributeObj.value.checkedDefaultCheckList);
    // console.log('选项:',attributeObj.value.defaultCheckList);
}, { deep: true });
onMounted(() => {
    handleCheckedChange(attributeObj.value.checkedDefaultCheckList);
})
</script>
<style scoped lang="scss">
.default-action {
    margin: 20px 0 0 30px;
    .select-all {
        display: flex;
        align-items: center;
    }

    .el-checkbox-group {
        display: flex;
        flex-direction: column;
        margin-left: 20px;
    }
}

.act-item {
    height: 35px;

    :deep(.el-checkbox__label) {
        padding-left: 15px;
        width: 100%;
    }
}
</style>
